<template>
  <div class="order-wrap">
    <div class="import-order"><span @click="importOrder">导入订单<i class="el-icon-arrow-right"></i></span></div>
    <section class="section-wrap">
      <div class="step">
        <div :class="['step1', active >= 0 ? 'success' : '']"
             @click="loading ? '' : stepActive(0)">
          <span class="num">1</span> 收发货信息
        </div>
        <div :class="['step2', active >= 1 ? 'success' : '']"
             @click="loading ? '' : stepActive(1)">
          <span class="num">2</span> 配置信息
        </div>
        <div :class="['step3', active >= 2 ? 'success' : '']"
             @click="loading ? '' : stepActive(2)">
          <span class="num">3</span> 货物信息
        </div>
      </div>
      <component :is="componentId"
                 ref="from"
                 class="form-box"
                 :form-info.sync="form"
                 :empty-form="emptyForm"
                 :chang-form-data="changFormData"
                 @loading="saveLoading"
                 @initActive="handleInitActive" />
      <div class="bottom-fixed-btn">
        <el-button type="primary"
                   class="butSty"
                   plain
                   @click="reset('from')">清 空</el-button>
        <el-button type="primary"
                   class="butSty"
                   plain
                   :loading="loading"
                   @click="draft('from')"
                   @loading="setLoading">存为草稿</el-button>
        <el-button v-if="active > 0"
                   type="primary"
                   plain
                   class="butSty"
                   @click="previous">上一步</el-button>
        <el-button v-if="active < 2"
                   type="primary"
                   class="butSty"
                   @click="next('from')">下一步</el-button>
        <el-button v-if="active > 1"
                   type="primary"
                   class="butSty"
                   :loading="loading"
                   @click="save('from')"
                   @loading="setLoading">提 交</el-button>
      </div>
    </section>
  </div>
</template>

<script>
import { FormData } from "./form.js";
import AddressInfo from "./AddressInfo.vue";
import GoodsInfo from "./GoodsInfo.vue";
import Transport from "./Transport.vue";
import { Storage } from "@/libs/storage";
import { order, customer, shippingAddress, consignee } from "@/api/index.js";


const componentName = {
  0: 'AddressInfo',
  1: 'Transport',
  2: 'GoodsInfo'
}

import { mapState } from "vuex";
export default {
  name: "CreateOrder",
  components: { AddressInfo, Transport, GoodsInfo },
  data () {
    return {
      rules: {},
      active: 0,
      loading: false,
      storage: new Storage("createForm", localStorage),
      tableData: [{}],
      form: new FormData(),
      showGoods: false, //物品组件
      componentId: "AddressInfo",
      emptyForm: {},
      userInfo: sessionStorage.getItem('userInfo')
    };
  },
  computed: {
    ...mapState({
      menuList: (state) => state.login.menuList
    }),
    user () {
      return JSON.parse(this.userInfo)
    },
    userId () {
      return this.user?.userId
    }
  },
  watch: {
    active: {
      immediate: true,
      handler (val) {
        this.componentId = componentName[val]
      }
    }
  },
  mounted () {
    if (this.$route.query.orderId) {
      this.getDetail();
    } else if (this.$route.query.draftId) {
      this.getOrderDraft();
    } else {
      let createForm = this.storage.read(`${this.userId}createForm`);
      if (createForm) {
        this.form = { ...this.form, ...createForm };
      } else if (this.form.customerId) {
        this.getConfig();
      }
      if (!this.form.customerId) {
        this.getCustomer(true);
      } else {
        this.getCustInfo(this.form.customerId);
      }
    }
    // 绑定窗口关闭[监听]事件
    window.addEventListener("beforeunload", this.beforeunloadHandler);
  },
  // mounted () {
  //   // 绑定窗口关闭[监听]事件
  //   window.addEventListener('beforeunload', this.beforeunloadHandler)
  // },
  beforeDestroy () {
    if (!this.form.id) {
      this.storage.write(`${this.userId}createForm`, this.form);
      // 解除窗口关闭[监听]事件
      window.removeEventListener("beforeunload", this.beforeunloadHandler);
    }
  },
  methods: {
    // 保存草稿
    async draft () {
      if (this.form.contractNo) {
        if (this.form.contractNo.match(/^[a-zA-Z0-9\-\_\(\)\&\+\/\[\]]{0,30}$/) == null) {
          return this.$message.error("合同编号只可输入数字、字母和特殊符号(-_()&+/[])");
        }
      } else {
        return this.$message.error("请输入合同编号");
      }
      console.log("=========this.form", this.form)
      /** 货物信息处理 */
      // let arr = this.form.goodsList.filter(item => item?.echo || item?.goodsId)
      // let arr = this.form.goodsList.filter((item) => {
      //   return item.goodsId;
      // });
      // let goodsList = JSON.parse(JSON.stringify(arr));

      /** 多式联运处理 */
      // 跟踪方式调整传值(未选择设备号或填写快递单号不传值给报表)
      let trackType = this.form.deviceCode ? this.form.trackType : null;
      let trackNo = trackType === 1
        ? this.form.deviceCode ? `35160808${this.form.deviceCode}` : null
        : this.form.deviceCode;
      let transportsArr = [];
      if (this.form.checkValue === 1 && this.form.flyNo) {
        transportsArr.push({
          route: {
            sequence: "1",
            startPlace: this.form.currentAddress[0].stationName,
            endPlace: this.form.currentAddress[1].stationName,
            transitNo: this.form.flyNo,
            startTime: this.form.flyTime,
          },
          type: 1
        });
        // if (this.form.receiptAddress.wayDistrictCode) {
        transportsArr.push({
          route: {
            ...this.form.receiptAddress,
            sequence: "2",
            deviceCode: this.form.thirdDeviceCode ? `35160808${this.form.thirdDeviceCode}` : trackNo,
          },
          type: 4
        });
        // }
      } else if (this.form.checkValue === 2 && this.form.trainNum) {
        transportsArr.push({
          route: {
            sequence: "1",
            startPlace: this.form.trainForm,
            endPlace: this.form.trainTo,
            transitNo: this.form.trainNum,
            startTime: this.form.trainTime,
          },
          type: 2
        });
        // if (this.form.receiptAddress.wayDistrictCode) {
        transportsArr.push({
          route: {
            ...this.form.receiptAddress,
            sequence: "2",
            deviceCode: this.form.thirdDeviceCode ? `35160808${this.form.thirdDeviceCode}` : trackNo,
          },
          type: 4
        });
        // }
      } else if (this.form.checkValue === 3) {
        transportsArr.push({
          route: {
            ...this.form.secordReceiptAddress,
            sequence: "1",
            deviceCode: `35160808${this.form.secondDeviceCode}`,
          },
          type: 4
        });
        if (this.form.isThirdShow) {
          transportsArr.push({
            route: {
              ...this.form.receiptAddress,
              sequence: "2",
              deviceCode: `35160808${this.form.thirdDeviceCode}`,
            },
            type: 4
          });
        }
      }
      this.loading = true;
      this.form.routes = [...transportsArr];
      if (!this.form.insure) this.form.insure = 0;
      // 物品总价值等于0，并且有复制的物品总价值时，物品总价值等于复制的总价值
      if (this.form.totalValue === 0 && this.form.calculateValue) this.form.totalValue = this.form.calculateValue
      this.$emit("loading", true);
      //去除上传附件-图片的预览url
      if (this.form.attachments.length) {
        let attachments = this.form.attachments.map(item => {
          return {
            type: 2,
            name: item.name || item.attachName,
            url: item.url || item.attachUrl
          }
        })
        this.form.attachments = attachments
      }
      /* transportMode 为1是零担业务，transportMode 为2是整车业务 */
      /* 所以为零担业务时 vehicle 参数要清除 */
      if (this.form.transportMode === 2) {
        this.form.vehicle = {
          model: this.form.vehicleMode?.vehicleType || null,
          length: this.form.vehicleMode?.vehicleLength || null,
          weight: this.form.vehicleMode?.vehicleWeight || null,
          volume: this.form.vehicleMode?.vehicleVolume || null,
          quantity: this.form.vehicleMode?.vehicleCount || null
        }
        this.form.pick = 0;
        this.form.deliver = 0;
        if (!this.form.onLoad && !this.form.offLoad) {
          this.form.priceUnit = null;
          this.form.chargeMode = null;
        }
      }
      /***** 订单优化相关字段名转化 *****/
      this.form = {
        ...this.form,
        cargoType: this.form.goodsCategory, // 货物分类
        billingUnit: this.form.priceUnit, //计价单位
        billingMode: this.form.chargeMode, //计费模式
        unload: this.form.offLoad,  // 卸货
        load: this.form.onLoad, //装货
        fromAddress: { // 发货信息
          ...this.form.fromAddress,
          contactMobile: this.form.fromContact.contactMobile,
          contactName: this.form.fromContact.contactName,
          precision: this.form.fromAddress.locationType,
        },
        toAddress: { // 收货信息
          ...this.form.toAddress,
          contactMobile: this.form.toContact.contactMobile,
          contactName: this.form.toContact.contactName,
          precision: this.form.toAddress.locationType,
        },
        differenceValue: this.form.valueAddition,
        differenceVolume: this.form.volumeAddition,
        differenceWeight: this.form.weightAddition,
      }

      let params = {
        ...this.form,
        // goodsList,
        trackNo,
        deviceCode: trackNo,
        trackType
      };
      let { data } = this.$route.query.draftId
        ? await order.updateOrderDraft(params)
        : await order.createOrderDraft(params);
      if (data.draftId) {
        this.loading = false;
        this.continueCreate();
        this.$message.success("订单草稿保存成功");
        this.run();
      }
    },
    run () {
      let menuList = JSON.parse(sessionStorage.getItem("ANYWHERE::MENU_TREE"));
      let menuId = menuList.find(i =>
        i.name === '订单管理' && i.children.length)?.children.find(x =>
          x.name === '订单草稿')?.menuId
      this.$router.push({
        path: `/board/${menuId}`,
      });
    },
    continueCreate () {
      // 去除路由参数
      let url = window.location.href; //获取当前页面的url
      if (url.indexOf("?") != -1) { //判断是否存在参数
        url = url.replace(/(\?|#)[^'"]*/, '');  //去除参数
        window.history.pushState({}, 0, url);
      }
      this.handleInitActive(0);
    },
    // 创建后不可点击头部事件
    setLoading (val) {
      this.loading = val;
      if (!this.form.customerId) {
        this.insertCustomer();
      }
      if (!this.form.consigneeId) {
        this.insertConsignee();
      }
    },
    // 获取客户id
    async getCustomer (flag) {
      let { data } = await customer.search({
        customerTypes: [0, 2],
        sort: [
          { name: 'type', asc: false },
          { name: 'hots', asc: false }
        ]
      });
      this.form.customerId = data.records[0]?.customerId;
      this.form.customerName = data.records[0]?.name;
      if (this.form.customerId) {
        this.getCustInfo(this.form.customerId);
        if (flag) this.getConfig();
      }
    },
    // 订单详情
    async getDetail () {
      let { data, code } = await order.orderDetailsApi(this.$route.query.orderId);
      if (code === 0) {
        this.form = new FormData();
        this.form = { ...this.form, ...data };
        /***** 订单优化相关字段名转化 *****/
        this.form.fromContact = { contactName: this.form.fromAddress?.contactName, contactMobile: this.form.fromAddress?.contactMobile }
        this.form.toContact = { contactName: this.form.toAddress?.contactName, contactMobile: this.form.toAddress?.contactMobile }
        this.form.onLoad = this.form.load || false;
        this.form.offLoad = this.form.unload || false;
        this.form.insure = this.form.insure ? 1 : 0;
        this.form.goodsCategory = this.form.cargoType;
        this.form.priceUnit = this.form.billingUnit;
        this.form.chargeMode = this.form.billingMode;
        this.form.valueAddition = this.form.differenceValue;
        this.form.volumeAddition = this.form.differenceVolume;
        this.form.weightAddition = this.form.differenceWeight;
        // 运输模式为整车
        if (this.form.transportMode === 2) {
          this.form.vehicleMode = {
            vehicleType: this.form.vehicle?.model,
            vehicleLength: this.form.vehicle?.length,
            vehicleWeight: this.form.vehicle?.weight,
            vehicleVolume: this.form.vehicle?.volume,
            vehicleCount: this.form.vehicle?.quantity,
          };
        }
        // 跟踪方式默认为电子回单
        if (!this.form.trackType) {
          this.form.trackType = 1;
        }
        this.$forceUpdate();
        //type 有值要清除部分值 type有值: 复制订单
        if (this.$route.query.type) {
          this.form.id = null;
          this.form.attachments = [];
          this.init();
        }
        // 复制创建订单总重量、体积、价值四舍五入
        if (this.form.calculateValue && (this.form.calculateValue).toString().indexOf('.') != -1) this.form.calculateValue = (this.form.calculateValue).toFixed(2)
        if (this.form.calculateVolume && (this.form.calculateVolume).toString().indexOf('.') != -1) this.form.calculateVolume = (this.form.calculateVolume).toFixed(2)
        if (this.form.calculateWeight && (this.form.calculateWeight).toString().indexOf('.') != -1) this.form.calculateWeight = (this.form.calculateWeight).toFixed(2)

        this.form.totalWeight = Number((this.form.totalWeight + this.form.weightAddition).toFixed(2));
        this.form.totalVolume = Number((this.form.totalVolume + this.form.volumeAddition).toFixed(2));
        this.form.totalValue = Number((this.form.totalValue + this.form.valueAddition).toFixed(2));
      }
    },
    // 订单草稿详情
    async getOrderDraft () {
      let { data, code } = await order.getOrderDraft(this.$route.query.draftId);
      if (code === 0) {
        this.form = new FormData();
        this.form = { ...this.form, ...data };
        /***** 订单优化相关字段名转化 *****/
        this.form.fromContact = { contactName: this.form.fromAddress?.contactName, contactMobile: this.form.fromAddress?.contactMobile }
        this.form.toContact = { contactName: this.form.toAddress?.contactName, contactMobile: this.form.toAddress?.contactMobile }
        this.form.onLoad = this.form.load || false;
        this.form.offLoad = this.form.unload || false;
        this.form.insure = this.form.insure ? 1 : 0;
        this.form.goodsCategory = this.form.cargoType;
        this.form.priceUnit = this.form.billingUnit;
        this.form.chargeMode = this.form.billingMode;
        this.form.valueAddition = this.form?.differenceValue || 0;
        this.form.volumeAddition = this.form.differenceVolume;
        this.form.weightAddition = this.form.differenceWeight;
        // 运输模式为整车
        if (this.form.transportMode === 2) {
          this.form.vehicleMode = {
            vehicleType: this.form.vehicle?.model,
            vehicleLength: this.form.vehicle?.length,
            vehicleWeight: this.form.vehicle?.weight,
            vehicleVolume: this.form.vehicle?.volume,
            vehicleCount: this.form.vehicle?.quantity,
          };
        }
        // if (this.form.transportMode === 2 && this.form.vehicleLength === 999)
        //   this.form.vehicleLength = "其他";

        // 跟踪方式默认为电子回单
        if (!this.form.trackType) {
          this.form.trackType = 1;
        }
        this.form.deviceCode = this.form.trackNo || null;
        if (this.form.trackType == 1) {
          this.form.deviceCode = this.form.deviceCode ? this.form.deviceCode.substring(8, this.form.deviceCode.length) : null;
        }
        const { routes } = this.form;
        if (routes && routes.length > 0) {
          this.form.checkValue = routes[0].type === 4 ? 3 : routes[0].type;
          this.form.receiptAddress = {
            wayCity: "",
            wayCityCode: "",
            wayDistrict: "",
            wayDistrictCode: "",
            wayProvince: "",
            wayProvinceCode: "",
            wayAddress: ""
          };
          this.form.secordReceiptAddress = { ...this.form.receiptAddress };
          if ([1, 2].includes(this.form.checkValue)) {
            this.form.currentAddress = [
              { stationName: routes[0].route.startPlace },
              { stationName: routes[0].route.endPlace }
            ];
            this.form.secondDeviceCode = routes[0].route.transitNo;
            if (this.form.checkValue == 1) {
              this.form.flyNo = routes[0].route.transitNo;
              this.form.flyTime = routes[0].route.startTime;
            } else if (this.form.checkValue == 2) {
              this.form.trainNum = routes[0].route.transitNo;
              this.form.trainTime = routes[0].route.startTime;
              this.form.trainForm = routes[0].route.startPlace;
              this.form.trainTo = routes[0].route.endPlace;
            }
            this.form.isThirdShow = false;
            this.form.deleteFlag = true;
            if (routes.length > 1) {
              this.form.isThirdShow = true;
              this.form.deleteFlag = false;
              this.form.thirdDeviceCode =
                routes[1].route.deviceCode.substring(
                  8,
                  routes[1].route.deviceCode.length
                );
              this.form.receiptAddress = { ...routes[1].route };
            }
          } else {
            let arr = [];
            routes.map((item, index) => {
              arr.push({ stationName: item.route.wayCity });
              if (index === 0) {
                this.form.secondDeviceCode = item.route.deviceCode.substring(
                  8,
                  item.route.deviceCode.length
                );
                this.form.secordReceiptAddress = { ...item.route };
                this.form.isThirdShow = false;
              } else {
                this.form.isThirdShow = true;
                this.form.thirdDeviceCode = item.route.deviceCode.substring(
                  8,
                  item.route.deviceCode.length
                );
                this.form.receiptAddress = { ...item.route };
              }
            });
            this.form.currentAddress = [...arr];
          }
        }
        this.$forceUpdate();

        let total = {
          totalQuantity: 0,
          totalWeight: 0,
          totalVolume: 0,
          totalValue: 0
        }
        this.form.goodsList.length && this.form.goodsList.map(item => {
          if (item.quantity) {
            total.totalQuantity += Number(item.quantity);
            total.totalWeight += Number(item.weight) * Number(item.quantity);
            total.totalVolume += Number(item.volume) * Number(item.quantity);
            total.totalValue += Number(item.value) * Number(item.quantity);
          }
        })
        this.form.totalQuantity = total.totalQuantity;
        this.form.calculateWeight = this.form.totalWeight = Number((total.totalWeight + this.form.weightAddition).toFixed(2));
        this.form.calculateVolume = this.form.totalVolume = Number((total.totalVolume + this.form.volumeAddition).toFixed(2));
        this.form.calculateValue = this.form.totalValue = Number((total.totalValue + this.form.valueAddition).toFixed(2));
      }
    },
    // 客户默认地址
    async getCustInfo (customerId) {
      if (customerId) {
        let { data: { records } } = await shippingAddress.search({ customerId, isDefault: true });
        let obj = records && records.length > 0 ? records[0] : null;
        if (obj) {
          this.form.fromAddress = Object.assign(this.form.fromAddress, obj);
          this.form.fromContact = Object.assign(this.form.fromContact, obj);
        } else {
          this.form.fromAddress = {
            address: null,
            city: null,
            cityCode: null,
            district: null,
            districtCode: null,
            province: null,
            provinceCode: null
          };
          this.form.fromContact = { contactName: null, contactMobile: null };
        }
      }
    },
    beforeunloadHandler (e) {
      e = e || window.Event;
      if (e) {
        e.returnValue = "系统可能不会保存信息";
      }
      return "系统可能不会保存信息";
    },
    // loading
    saveLoading (val) {
      this.loading = val;
    },
    // 根据客户获取配置信息
    async getConfig () {
      let { data } = await order.getCreateConfig(this.form.customerId);
      if (data) {
        data.goodsCategory = data.goodsCategory === 0 ? null : data.goodsCategory;
        data.packageMode = data.packageMode === 0 ? null : data.packageMode;
        data.chargeMode = data.chargeMode || 2;
        data.priceUnit = data.priceUnit || 3;
        data.goodsType = data.goodsType + '';
        Object.assign(this.form, data);
      } else {
        const obj = {
          transportMode: 1,
          chargeMode: 2,
          priceUnit: 3,
          pick: false, deliver: false, onLoad: false, offLoad: false, insure: null, packageMode: null, goodsType: null, goodsCategory: null
        };
        Object.assign(this.form, obj);
      }
      this.form.vehicleMode.vehicleCount = 1;
    },
    save (formName) {
      this.$refs[formName].save();
    },
    // step事件
    stepActive (active) {
      this.active = active;
      if ([1, 2].includes(this.active)) {
        this.getLocation("fromAddress");
        this.getLocation("toAddress");
      }
      const { consigneeName, customerName, toContact, fromContact } = this.form
      if (consigneeName && toContact?.contactName && toContact?.contactMobile) {
        this.insertConsignee();
      }
      if (customerName && fromContact?.contactName && fromContact?.contactMobile) {
        this.insertCustomer();
      }
      // if (active === 0) {
      //   this.active = active;
      // } else if (active === 1) {
      //   if (this.active === 0) {
      //     this.next("from");
      //   } else {
      //     this.active = active;
      //   }
      // }
    },
    // 上一步
    previous () {
      this.active = --this.active;
    },
    // 初始话active
    handleInitActive (value) {
      this.active = value;
      this.form = new FormData();
      this.getCustomer(true);
    },
    // 动态化组件
    changFormData (value) {
      this.formData = value;
    },
    // 下一步
    next (formName) {
      this.$refs[formName].childSubmit().then((valid) => {
        if (valid) {
          const { consigneeName, customerName, toContact, fromContact } = this.form
          if (this.active + 1 === 2) {
            // if (
            //   [1, 2].includes(this.form.checkValue) &&
            //   !this.form.deleteFlag
            // ) {
            //   if (
            //     this.form.thirdDeviceCode ||
            //     this.form.receiptAddress.wayCityCode ||
            //     this.form.receiptAddress.wayAddress
            //   ) {
            //     if (!this.form.thirdDeviceCode)
            //       return this.$message.warning("请选择电子回单！");
            //     if (!this.form.receiptAddress.wayCityCode)
            //       return this.$message.warning("请选择途径地区！");
            //     if (!this.form.receiptAddress.wayAddress)
            //       return this.$message.warning("请输入详细地址！");
            //   }
            // }
            if (this.form.checkValue === 3) {
              if (!this.form.secondDeviceCode)
                return this.$message.warning("请选择电子回单！");
              if (!this.form.secordReceiptAddress.wayCityCode)
                return this.$message.warning("请选择途径地区！");
              if (!this.form.secordReceiptAddress.wayAddress)
                return this.$message.warning("请输入详细地址！");

              if (this.form.isThirdShow) {
                if (!this.form.thirdDeviceCode)
                  return this.$message.warning("请选择电子回单！");
                if (!this.form.receiptAddress.wayCityCode)
                  return this.$message.warning("请选择途径地区！");
                if (!this.form.receiptAddress.wayAddress)
                  return this.$message.warning("请输入详细地址！");
              }
            }
          }
          if (this.active === 0) {
            this.getLocation("fromAddress");
            this.getLocation("toAddress");
            // if (
            //   this.$moment(this.form.fromTime).format("YYYY-MM-DD HH:mm") ===
            //   this.$moment(this.form.toTime).format("YYYY-MM-DD HH:mm")
            // ) {
            //   return this.$message.error("发货时间需早于收货时间");
            // }
            this.handleRepeatPactCode();
            if (consigneeName && toContact?.contactName && toContact?.contactMobile) {
              this.insertConsignee();
            }
            if (customerName && fromContact?.contactName && fromContact?.contactMobile) {
              this.insertCustomer();
            }
          }
          // if (!this.form.customerId || !this.form.consigneeId) {
          //   if (!this.form.customerId) {
          //     this.insertCustomer();
          //   }
          //   if (!this.form.consigneeId) {
          //     this.insertConsignee();
          //   }
          //   this.active = ++this.active;
          // } 
          if (!this.form.fromAddress?.provinceName && !this.form.fromAddress?.provinceCode) {
            // 发货省市区
            this.$message.error('请选择发货省市区');
          } else if (!this.form.toAddress?.provinceName && !this.form.toAddress?.provinceCode) {
            // 收货省市区
            this.$message.error('请选择收货省市区');
          }
          else {
            this.active = ++this.active;
          }
          // if (!this.form.customerId || !this.form.consigneeId) {
          //   if (!this.form.customerId) {
          //     this.insertCustomer();
          //   }
          //   if (!this.form.consigneeId) {
          //     this.insertConsignee();
          //   }
          //   this.active = ++this.active;
          // } else if (!this.form.fromAddress?.provinceName && !this.form.fromAddress?.provinceCode) {
          //   // 发货省市区
          //   this.$message.error('请选择发货省市区');
          // } else if (!this.form.toAddress?.provinceName && !this.form.toAddress?.provinceCode) {
          //   // 收货省市区
          //   this.$message.error('请选择收货省市区');
          // }
          // else {
          //   this.active = ++this.active;
          // }
        }
      });
    },
    //合同重复校验
    async handleRepeatPactCode () {
      if (!this.form.contractNo) {
        return;
      }
      let { code, data } = await order.validateRepeatContractNo({
        contractNo: encodeURIComponent(this.form.contractNo)
      });
      if (code === 0 && !data) {
        this.$message.warning("合同编号与已存在的订单合同编号重复！");
      }
    },
    // 新增客户
    async insertCustomer () {
      let postData = {
        name: this.form.customerName,
        contactMobile: this.form.fromContact.contactMobile,
        contactName: this.form.fromContact.contactName
      };
      let { data, code } = await customer.insertShould(postData);
      if (code !== 0)
        this.$message.error("已为您找到了相同的发货方名称信息，请重新选择");
      else {
        this.form.customerId = data?.customerId;
        // if (!this.form.consigneeId && data?.customerId) {
        //   this.insertConsignee(data?.customerId);
        // } else {
        //   // this.active = ++this.active;
        // }
      }
    },
    // 新增收货方
    async insertConsignee (customerId) {
      if (!customerId && !this.form.customerId) return false;
      let postData = {
        customerId: this.form.customerId || customerId,
        customerName: this.form.customerName,
        name: this.form.consigneeName,
        contactMobile: this.form.toContact.contactMobile,
        contactName: this.form.toContact.contactName
      };
      let { data } = await consignee.insertShould(postData);
      // this.active = ++this.active;
      this.form.consigneeId = data?.consigneeId;
    },
    // 获取经纬度
    async getLocation (address) {
      this.form[address].provinceName = this.form[address].province;
      this.form[address].districtName = this.form[address].district;
      this.form[address].cityName = this.form[address].city;

      let { data } = await order.analysisAddress({
        address: this.form[address]?.address,
        city: this.form[address]?.city,
        district: this.form[address]?.district,
        province: this.form[address]?.province,
        locate: true
      });
      this.form[address].locationType = data?.precision;
      this.form[address].location = `${data?.lon},${data?.lat}`;
    },
    // 初始化
    init () {
      this.form.deviceCode = null;
      this.form.trackType = 1;
      this.form.currentAddress = [];
      this.form.receiptAddress = {
        wayCity: "",
        wayCityCode: "",
        wayDistrict: "",
        wayDistrictCode: "",
        wayProvince: "",
        wayProvinceCode: "",
        wayAddress: ""
      };
      this.form.secordReceiptAddress = { ...this.form.receiptAddress };
      this.form.checkValue = null;
      this.form.secondDeviceCode = "";
      this.form.thirdDeviceCode = "";
      this.form.isThirdShow = true;
      this.form.flyNo = null;
      this.form.flyTime = null;
      this.form.trainNum = null;
      this.form.trainTime = null;
      this.form.trainForm = null;
      this.form.trainTo = null;
    },
    // 清空
    reset (formName) {
      this.$confirm("确认清空页面上已填信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 去除路由参数
        let url = window.location.href; //获取当前页面的url
        if (url.indexOf("?") != -1) { //判断是否存在参数
          url = url.replace(/(\?|#)[^'"]*/, '');  //去除参数
          window.history.pushState({}, 0, url);
        }
        // 清空缓存
        this.storage.write(`${this.userId}createForm`, {});
        // 清空当前页面
        this.$refs[formName].resetInfo();
      });
    },
    importOrder () {
      this.$router.push("/OrderImport");
    }
  }
};
</script>

<style lang="scss" scoped>
.order-wrap {
  // height: calc(100vh - 90px);
  transform: translate(0, 0);
}
.section-wrap {
  background: var(--prev-bg-white);
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 170px);
}

.bottom-fixed-btn {
  text-align: center;
  position: absolute;
  width: 100%;
  bottom: 0;
  background: var(--prev-bg-white);
  left: 0;
  padding-bottom: 20px;
  z-index: 9;
}
.step {
  width: 762px;
  margin: 0 auto;
  padding: 0px 10px;
  margin-bottom: 40px;
  display: flex;
  font-size: 16px;
  font-weight: bold;
  > div {
    flex-grow: 1;
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: var(--prev-color-text-grey);
    margin-left: -12px;
    width: 266px;
    cursor: pointer;
    .num {
      width: 20px;
      height: 20px;
      line-height: 20px;
      border-radius: 50%;
      text-align: center;
      margin-right: 10px;
      color: var(--prev-bg-white);
      background: var(--prev-color-text-grey);
    }
    &.success {
      color: var(--prev-bg-white);
      .num {
        background: var(--prev-bg-white);
        color: var(--prev-icon-color-orange);
      }
    }
  }
  .step1 {
    // background: transparent url("@/static/images/createOrderGrey01.png")
    //   no-repeat;
    background: transparent url("../../../static/images/createOrderGrey01.png")
      no-repeat;
    background-size: 100% auto;
    &.success {
      background: transparent
        url("../../../static/images/createOrderOrange01.png") no-repeat;
      background-size: 100% auto;
    }
  }
  .step2 {
    background: transparent url("../../../static/images/createOrderGrey02.png")
      no-repeat;
    background-size: 100% auto;
    &.success {
      background: transparent
        url("../../../static/images/createOrderOrange02.png") no-repeat;
      background-size: 100% auto;
    }
  }
  .step3 {
    background: transparent url("../../../static/images/createOrderGrey03.png")
      no-repeat;
    background-size: 100% auto;
    &.success {
      background: transparent
        url("../../../static/images/createOrderOrange03.png") no-repeat;
      background-size: 100% auto;
    }
  }
  .mlr10 {
    margin: 0 10px;
  }
}
.butSty {
  height: 36px;
}
.import-order {
  height: 40px;
  background: #fafafa;
  display: flex;
  justify-content: right;
  align-items: center;
  cursor: pointer;
  span {
    color: var(--prev-color-primary);
  }
  i {
    padding: 0 20px 0 5px;
  }
}
</style>
